<?php

namespace app\admin\controller\staff;

use app\admin\model\Admin;
use app\admin\model\CalendarEvent;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 员工排版
 *
 * @icon fa fa-circle-o
 */
class Staffclass extends Backend
{

    /**
     * Staffclass模型对象
     * @var \app\admin\model\staff\Staffclass
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\staff\Staffclass;
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        // $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 查看
     */
    public function index()
    {
        $adminList = Admin::where('id', 'in', $this->childrenAdminIds)->field('id,username as name')->select();
        $this->assignconfig('admins', $adminList);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $start = $this->request->get('start');
            $end = $this->request->get('end');
            $type = $this->request->get('type');
            $staff_id = $this->request->get('staff_id');

            $where = [];
            if ($staff_id) {
                $where['staff_id'] = $staff_id;
               // $staff_id = $type == 'my' ? $this->auth->id : 0;
            }
            $list = $this->model
                ->where($where)
                ->where(function ($query) use ($start, $end) {
                    $startTime = strtotime($start);
                    $endTime = strtotime($end);
                    $query->where("`starttime` BETWEEN {$startTime} AND {$endTime}");
                    $query->whereOr("`endtime` BETWEEN {$startTime} AND {$endTime}");
                    $query->whereOr("`starttime` < {$startTime} AND `endtime` > {$endTime}");
                })
                ->order('id desc')
                ->select();
            $result = [];
            $time = time();
            foreach ($list as $k => $v) {
                $result[] = $v['render'];
            }

            return json($result);
        }

        return $this->view->fetch();
    }

    public function add()
    {
        $datetime = $this->request->param('datetime');
        if (empty($datetime)) {
            $this->error('请选择日期');
        }
        $datetime = strtotime($datetime);
        $class = Db::name('classes')->field('id,name,starttime,endtime')
            ->where('deletetime', null)
            ->where('status', 'normal')->select();

        foreach ($class as $k => &$v) {
            $v['staff'] = Db::name('staff_class c')
                ->field('c.id as cid,c.staff_id,s.name,s.id')
                ->join('staff s', 's.id= c.staff_id', 'left')
                ->where(['classes_id' => $v['id'], 'deletetime' => null,'scheduletime'=> $datetime])
                ->select();
        }
        $this->assign('time', date('Y年m月d日', $datetime));
        $this->assign('datetime',  $datetime);
        $this->assign('class', $class);
        return $this->view->fetch();


    }

    /**
     * 编辑日历
     */
    public function edit($ids = null)
    {
        return $this->view->fetch();
    }

    /**
     * 编辑日历
     */
    public function staff()
    {
        $date = $this->request->param();
        $this->assign('datetime', date('Y-m-d', $date['datetime']));
        $this->assign('dateid', $date['dateid']);
        return $this->view->fetch();
    }

    /**
     * 删除日历
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error("invalid request");
        }
        if ($ids) {
            $count = $this->model->where('admin_id', 'in', $this->childrenAdminIds)->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量操作
     */
    public function multi($ids = '')
    {
        if (!$this->request->isPost()) {
            $this->error("invalid request");
        }
        $ids = $this->request->post("ids");
        $date = $this->request->post("date");
        if ($ids || $date) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {
                    $count = $this->model->where($this->model->getPk(), 'in', $ids)->where('admin_id', 'in', $this->childrenAdminIds)->update($values);
                    $this->success();
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function add_staff()
    {
        $staff_id = $this->request->param('staff_id');
        $date = $this->request->param('datetime');
        $dateid = $this->request->param('dateid');
        $class = Db::name('classes')->where('id', $dateid)->find();

        $start = date('Y-m-d', strtotime($date)) . $class['starttime'];
        $end = date('Y-m-d', strtotime($date)) . $class['endtime'];
        $find = Db::name('staff_class')->where(['staff_id'=>$staff_id,'classes_id'=>$dateid,'scheduletime'=>strtotime($date)])->find();

        if ($find) {
            $this->error('该员工已经排班');
        }
        $data = [
            'staff_id'     => $staff_id,
            'classes_id'   => $dateid,
            'scheduletime' => strtotime($date),
            'starttime'    => strtotime($start),
            'endtime'      => strtotime($end),
            'background'   => '#605ca8'
        ];

        Db::name('staff_class')->insert($data);
        $this->success();
    }

    /**
     * @throws PDOException
     * @throws Exception
     */
    public function del_staff(){
        $ids = $this->request->param('ids');
        $res = Db::name('staff_class')->where('id', $ids)->delete();
        $this->success();
    }


}
